/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rainful;

import com.caucho.hessian.client.HessianProxyFactory;
import rainful.echo.Echo;
import java.util.logging.Level;
import java.util.logging.Logger;
import rainful.echo.DefaultEchoSpace;
import rainful.echo.EchoSpace;

/**
 *
 * @author Administrator
 */
public class TalkAgent {
    public EchoSpace space;

    public TalkAgent() {
        space = new DefaultEchoSpace();
    }

    public TalkAgent(EchoSpace space) {
        this.space = space;
    }

    public Echo listen(Echo echo) throws AbortException {
        try {
            echo.counting();
            if (TalkSubjectManager.getInstance().exist(echo)) {
                return TalkSubjectManager.getInstance().get(echo).refect(echo);
            } else {
                throw new AbortException("can't find subject " + echo.getSubjectName());
            }
        } catch (Exception e) {
            Logger.getLogger(TalkAgent.class.getName()).log(Level.SEVERE, null, e);
            throw new AbortException(e);
        }
    }

    public Echo ask(String remoteURL, String subjectName) throws AbortException {
        return ask(remoteURL, new Echo(subjectName));
    }

    public Echo ask(String remoteURL, Echo echo) throws AbortException {
        try {
            HessianProxyFactory factory = new HessianProxyFactory();
            TalkAction action = (TalkAction) factory.create(TalkAction.class, remoteURL);
            do {
                echo = action.ask(echo);
                echo.execute(this.space);
                //*TODO 未來可以放一個callback function在這
            }while (!echo.isFinish());
            return echo;
        } catch (Exception ex) {
            Logger.getLogger(TalkAgent.class.getName()).log(Level.SEVERE, null, ex);
            throw new AbortException(ex);
        }
    }
}
